package net.dgg.zz.common.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.dgg.commons.qds.model.LoginUser;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.iboss.base.service.ScGeneralService;
import net.dgg.iboss.base.util.DateUtil;
import net.dgg.iboss.base.util.DesUtil;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.tmd.foundation.platform.user.service.UserService;
import net.dgg.zz.api.credential.entity.CertificateProductConfiguration;
import net.dgg.zz.api.credential.service.CertificateProductConfigurationService;
import net.dgg.zz.common.base.entity.BaseEntity;
import net.dgg.zz.common.base.service.BaseService;
import net.dgg.zz.common.constant.ScNoteType;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.constant.SystemCommonConstant;
import net.dgg.zz.common.dao.ProductDao;
import net.dgg.zz.common.entity.*;
import net.dgg.zz.common.excption.CommonExcption;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.DateUtils;
import net.dgg.zz.common.utils.MQMessageSendUtil;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.common.utils.ValidateUtils;
import net.dgg.zz.production.entity.ProductOrder;
import net.dgg.zz.production.entity.ProductTimeStatus;
import net.dgg.zz.production.entity.UnderOder;
import net.dgg.zz.production.inProcess.dao.*;
import net.dgg.zz.production.inProcess.entity.ProductData;
import net.dgg.zz.production.inProcess.entity.ProductNode;
import net.dgg.zz.production.inProcess.entity.ProductNodeOperating;
import net.dgg.zz.production.inProcess.service.ZzInProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;

import javax.transaction.Transactional;
import java.util.*;

/**
 * 接口service
 * <p>@Package: net.dgg.zz.common.service</p>
 * <p>@Title：OrderApiService</p>
 * <p>@description:</p>
 * <p>@author liulei</p>
 * <p>@date 2018年8月31日</p>
 * <p>@Company dgg</p>
 */
@Service
public class OrderApiService extends BaseService{


    @Autowired
    private CmsService smsservice;

    @Autowired
    private OrderService orderservice;

    @Autowired
    private ProductService productservice;
    /**
     * 生产订单dao
     */
    @Autowired
    private ProductOrderDao productOrderDao;


    @Autowired
    private UserService userService;
    @Autowired
    private CommonService commonService;


    @Autowired
    private ProductTimeStatusDao producttimestatusdao;

    /**
     * 注册接口
     */
    @Autowired
    private CommonMangerExtService commonMangerExtService;

    @Autowired
    private SystemRecordService systemRecordService;


    /**
     *
     */
    @Autowired
    private ProductDataDao productdatadao;
    /**
     * 办理节点
     */
    @Autowired
    private ProductNodeFlowDao nodeFlowDao;

    @Autowired
    private DesUtil desUtil;

    @Autowired
    private ScGeneralService scGeneralService;

    @Autowired
    private FlowService flowService;

    @Autowired
    private ProductDao productDao;
    /**
     * 超期表
     */
    @Autowired
    private ProductTimeStatusDao productTimeStatusDao;
    @Autowired
    private ZzInProcessService zzInProcessService;
    @Autowired
    private ProductNodeOperatingDao productNodeOperatingDao;
    @Autowired
    private ProductNodeDao productNodeDao;
    @Autowired
    private CertificateProductConfigurationService certificateProductConfigurationService;
    @Autowired
    private UnderOrderDao underOrderDao;
    /**
     * iboos插入资质生产接口
     *
     */
    @Transactional
    @SuppressWarnings({"unchecked", "rawtypes"})
    public String insertOrder(String zzOrderMap, String zzProductMapList)  {
        Long curentUserId = 1L;//当前登录用户id,超级管理员
        UserEntity userentity;//当前登录人
        Map curentDept;//当前登录人部门
        JSONObject orderObj = JSONObject.parseObject(zzOrderMap);
        if (StringUtils.isNotEmpty(orderObj.get("createrId"))){
            //传过来的创建者
            userentity = userService.findUserById(Long.valueOf(orderObj.get("createrId").toString()));
            curentDept = this.commonMangerExtService.findOrg(userentity.getOrgId());
        }else {
            //超级管理员
            userentity = userService.findUserById(curentUserId);
            curentDept = this.commonMangerExtService.findOrg(userentity.getOrgId());
        }
        Order order = orderservice.selectByOrderId(orderObj.get("orderId") == null ? null : orderObj.getLong("orderId"));
        if(null == order) {
        	order = new Order();
        	String customerPhone = "";
        	String contactPhone = "";
        	if(!StringUtils.isEmpty(orderObj.get("customerPhone"))) {
        		customerPhone = orderObj.get("customerPhone").toString();
        	}
        	if(!StringUtils.isEmpty(orderObj.get("contactPhone"))) {
        		contactPhone = orderObj.get("contactPhone").toString();
        	}
            //销售订单map
            order.setId(DggKeyWorker.nextId());//唯一主键
            order.setOrderId(orderObj.get("orderId") == null ? null : orderObj.getLong("orderId"));
            order.setOrderNo(orderObj.get("orderNo").toString());
            order.setScOrderNo(orderObj.get("scOrderNo").toString());
            order.setBusinessId(orderObj.get("businessId") == null ? null : orderObj.getLong("businessId"));
            order.setBusinessNo(orderObj.get("businessNo") == null ? null : orderObj.getString("businessNo") );
            order.setCustomerId(orderObj.get("customerId") == null ? null : orderObj.getLong("customerId"));
            order.setCustomerNo(orderObj.get("customerNo") == null ? null : orderObj.getString("customerNo") );
            order.setCustomerPhone(customerPhone);
            order.setCustomerName(orderObj.get("customerName") == null ? null : orderObj.getString("customerName"));
            order.setContactPhone(contactPhone);
            order.setBusinessTypeId(orderObj.get("businessTypeId") == null ? null : orderObj.getString("businessTypeId"));
            order.setBusinessTypeName(orderObj.get("businessTypeName") == null ? null : orderObj.getString("businessTypeName"));
            order.setSignUserId(orderObj.get("signUserId") == null ? null : orderObj.getLong("signUserId"));
            order.setSignUserName(orderObj.get("signUserName") == null ? null : orderObj.getString("signUserName"));
            Long signOrgId = orderObj.get("signOrgId") == null ? null : orderObj.getLong("signOrgId");
            if (null != signOrgId) {
                Map deptMap = this.commonMangerExtService.findOrg(signOrgId);
                if (null != deptMap) {
                    order.setSignUserOrgId(Long.parseLong(deptMap.get("id").toString()));
                    order.setSignUserOrgName(deptMap.get("name").toString());
                }
            }
            order.setSignOrgId(orderObj.get("sourceDeptId") == null ? null : orderObj.getLong("sourceDeptId"));
            order.setSignOrgName(orderObj.get("sourceDeptName") == null ? null : orderObj.getString("sourceDeptName"));
            order.setMoney(orderObj.get("money") == null ? null : orderObj.getBigDecimal("money"));
            order.setPayStatus(orderObj.get("payStatus") == null ? null : orderObj.getString("payStatus"));
            order.setPayMethod(orderObj.get("payMethod") == null ? null : orderObj.getString("payMethod"));
            order.setContractNo(orderObj.get("contractNo") == null ? null : orderObj.getString("contractNo"));
            order.setSignDate(orderObj.get("signDate") == null ? null : orderObj.getDate("signDate"));

            order.setCreaterId(userentity.getId());
            order.setCreaterName(userentity.getRealName());
            order.setCreateTime(new Date());
            order.setCreaterOrgId(null == curentDept ? null : Long.parseLong(curentDept.get("id").toString()));
            order.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            orderservice.ibossInsert(order);//插入销售订单
            //声明一个空的生产子订单ID
            Long scOrderId = null;
            //声明一个空的生产子订单编号
            String scOrderNo = null;
            JSONArray productList = JSONObject.parseArray(zzProductMapList);
            for (int i = 0; i < productList.size(); i++) {

                String productString = productList.getString(i);
                JSONObject productObj = JSONObject.parseObject(productString);
                //判断是否已经存在,如果存在不再写入


                Product product = new Product();//销售产品子订单
                product.setId(DggKeyWorker.nextId());
                product.setOrderId(order.getOrderId());

                product.setOrderBusinessId(productObj.get("orderBusId") == null ? null : productObj.getLong("orderBusId"));
                product.setBusinessTypeId(productObj.get("businessTypeId") == null ? null : productObj.getString("businessTypeId"));
                product.setOrderBusinessNo(productObj.get("orderBusNo") == null ? null : productObj.getString("orderBusNo"));
                product.setBusinessTypeName(productObj.get("businessTypeName") == null ? null : productObj.getString("businessTypeName"));
                //这个关键字段必须要有值
                ValidateUtils.strNotEmpty(productObj.get("businessProductId"), CommonExcption.class, "该子订单没有业态CODE,无法下单!");
                product.setBusinessProductCode(productObj.getString("businessProductId"));
                product.setBusinessProductName(productObj.get("businessProductName") == null ? null : productObj.getString("businessProductName"));
                product.setProductId(productObj.get("productId") == null ? null : productObj.getLong("productId"));
                product.setProductName(productObj.get("productName") == null ? null : productObj.getString("productName"));
                product.setProductAttr(productObj.get("productAttr") == null ? null : productObj.getString("productAttr"));
                product.setServiceAreaId(productObj.get("serviceAreaId") == null ? null : productObj.getLong("serviceAreaId"));
                product.setServiceArea(productObj.get("serviceArea") == null ? null : productObj.getString("serviceArea"));

                product.setContractNo(productObj.get("contractNo") == null ? null : productObj.getString("contractNo"));
                product.setOrderTime(productObj.get("orderTime") == null ? null : productObj.getDate("orderTime"));
                product.setMoney(productObj.get("money") == null ? null : productObj.getBigDecimal("money"));
                product.setPayMethod(productObj.get("payMethod") == null ? null : productObj.getString("payMethod"));
                //这个证书用的费用状态写死
                product.setCostState("NOT_APPLAY");
                product.setProductOrgId(productObj.get("productOrgId") == null ? null : productObj.getLong("productOrgId"));
                product.setProductOrgName(productObj.get("productOrgName") == null ? null : productObj.getString("productOrgName"));

                product.setCreaterId(userentity.getId());
                product.setCreaterName(userentity.getRealName());
                product.setCreateTime(new Date());
                product.setCreaterOrgId(null == curentDept ? null : Long.parseLong(curentDept.get("id").toString()));
                product.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());

                //生产订单表
                ProductOrder productOrder = new ProductOrder();
                Long no = DggKeyWorker.nextId();
                productOrder.setId(no);
                //只给声明的生产子订单ID赋值一次，以供同步数据到生产主订单库使用
                if(null == scOrderId){
                    scOrderId =no;
                }
                String number = smsservice.getBillNumber("sc");
                if (StringUtils.isEmpty(number)) {
                    //return "单据号获取失败,请联系管理员";
                    ValidateUtils.isTrue(StringUtils.isNotEmpty(number), CommonExcption.class, "单据号获取失败,请联系管理员");
                }
                productOrder.setScProductOrderNo(number);
                //只给声明的生产子订单编号赋值一次，以供同步数据到生产主订单库使用
                if(null == scOrderNo){
                    scOrderNo = number;
                }
                productOrder.setOrderId(order.getOrderId());
                productOrder.setOrderNo(order.getOrderNo());
                productOrder.setOrderBusId(productObj.get("orderBusId") == null ? null : productObj.getLong("orderBusId"));
                productOrder.setOrderBusNo(productObj.get("orderBusNo") == null ? null : productObj.getString("orderBusNo"));
                productOrder.setBusinessId(order.getBusinessId());
                productOrder.setBusinessNo(order.getBusinessNo());
                productOrder.setCustomerId(order.getCustomerId());
                productOrder.setCustomerNo(order.getCustomerNo());
                productOrder.setCustomerPhone(order.getCustomerPhone());
                productOrder.setCustomerName(order.getCustomerName());
                productOrder.setContactPbone(order.getContactPhone());
                productOrder.setProductOrgId(product.getProductOrgId());
                productOrder.setProductOrgName(product.getProductOrgName());
                productOrder.setBusinessTypeCode(product.getBusinessTypeId());
                productOrder.setBusinessTypeName(product.getBusinessTypeName());
                productOrder.setBusinessProductCode(product.getBusinessProductCode());
                productOrder.setBusinessProductName(product.getBusinessProductName());
                productOrder.setProductId(product.getProductId());
                productOrder.setProductName(product.getProductName());
                productOrder.setChannelId(productObj.get("channelId") == null ? null : productObj.getLong("channelId"));
                productOrder.setChannelName(productObj.get("channelName") == null ? null : productObj.getString("channelName"));
                productOrder.setContractNo(product.getContractNo());
                productOrder.setOrderTime(product.getOrderTime());
                productOrder.setMoney(product.getMoney());
                productOrder.setPayMethod(product.getPayMethod());
                productOrder.setSignUserId(order.getSignUserId());
                productOrder.setSignUserName(order.getSignUserName());
                productOrder.setContractNo(order.getContractNo());
                productOrder.setSignUserOrgId(order.getSignUserOrgId());
                productOrder.setSignUserOrgName(order.getSignUserOrgName());
                productOrder.setSignOrgId(order.getSignOrgId());
                productOrder.setSignOrgName(order.getSignOrgName());
                productOrder.setSignTime(order.getSignDate());///签单时间需要增加此字段
                productOrder.setStatus(ScProductConstant.SC_TO_RECEIVE_XDDJS);//下单待分配
                productOrder.setRemark(productObj.get("remark") == null ? null : productObj.getString("remark"));
                productOrder.setCreaterId(userentity.getId());
                productOrder.setCreaterName(userentity.getRealName());
                productOrder.setCreateTime(new Date());
                productOrder.setCreaterOrgId(null == curentDept ? null : Long.parseLong(curentDept.get("id").toString()));
                productOrder.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
                productOrder.setSignTime(order.getSignDate());
                productOrder.setReceiveOrderDate(new Date());
                productOrder.setOrderRemark(productObj.get("remark") == null ? null : productObj.getString("remark"));
                //插入流程id
                String flowStr = flowService.getFlowNodeStr(product.getProductId().toString(), product.getBusinessTypeId(), product.getProductOrgId(),product.getBusinessProductCode());
                ValidateUtils.isTrue(StringUtils.isNotEmpty(flowStr), CommonExcption.class, "未查询到" + product.getBusinessTypeName() + "[" + product.getProductName() + "]流程节点的配置信息,请联系对应事业部后台负责人");
                List<Node> nodeList = flowService.getNodeByFlowContent(flowStr);
                Node nodeNew = new Node();
                if (!"BUS_YT_ZZ_ZS".equals(product.getBusinessProductCode())) {
                    Node nodeNew1 = new Node();
                    for (Node node : nodeList) {
                        if ("分配".equals(node.getName())) {
                            nodeNew = node;
                        }
                        if ("接单".equals(node.getName())) {
                            nodeNew1 = node;
                        }
                    }
                    ValidateUtils.isTrue(StringUtils.isNotEmpty(nodeNew.getName()), CommonExcption.class, "未查询到[" + product.getProductName() + "]的分配节点的信息,请联系对应事业部后台负责人");
                    ValidateUtils.isTrue(StringUtils.isNotEmpty(nodeNew1.getName()), CommonExcption.class, "未查询到到[" + product.getProductName() + "]的接单节点的信息,请联系对应事业部后台负责人");
                } else {
                    for (Node node : nodeList) {
                        if ("证书入库".equals(node.getName())) {
                            nodeNew = node;
                        }
                    }
                    ValidateUtils.isTrue(StringUtils.isNotEmpty(nodeNew.getName()), CommonExcption.class, "未查询到到[" + product.getProductName() + "]的证书入库节点的信息,请联系对应事业部后台负责人");
                }
                Node node = nodeNew;
                productOrder.setFlowContent(flowStr);
                Map map = flowService.getOderCycle(productOrder);
                productOrder.setCurrentNodeId(node.getCode());
                productOrder.setCurrentNodeName(node.getName());
                productOrder.setLatestEndNodeId(node.getId().toString());
                productOrder.setLatestEndNodeName(node.getName());
                productOrderDao.iboosInsertSelective(productOrder);
                product.setRelevanceCredential(0);
                product.setCostState(ScProductConstant.NOT_APPLAY);
                product.setScProductOrderId(productOrder.getId());
                product.setScProductOrderNo(productOrder.getScProductOrderNo());
                productservice.iboosInsertProduct(product);

                //插入操作记录
                SystemRecord record = new SystemRecord();
                record.setId(DggKeyWorker.nextId());//id
                record.setSource("3");
                record.setWorkTableName("zzsc_product_order");
                record.setWorkId(productOrder.getId());
                record.setWorkNo(productOrder.getScProductOrderNo());
                record.setBeOperaterId(curentUserId);
                record.setOperateType("1");
                record.setRemarks("新增生产订单");
                systemRecordService.apiSave(record, userentity);

                //生产订单超期
                ProductTimeStatus timestatus = new ProductTimeStatus();
                timestatus.setId(productOrder.getId());
                timestatus.setScProductOrderNo(productOrder.getScProductOrderNo());
                timestatus.setDistributionStartTime(new Date());//计时开始时间
                timestatus.setDistributionTimeOutStatus(ScProductConstant.NORMAL);
                timestatus.setFlag(1);//必须要加入
                //写入分配节点
                Integer hours = 0;
                if (null != node) {
                    timestatus.setNodeId(node.getCode());
                    timestatus.setNodeName(node.getName());
                    hours = node.getHandleDate();
                    timestatus.setNodeProcessTimeType(node.getIsNaturalorWorkday());
                    timestatus.setNodeStartTime(new Date());
                    long millisecond = 0l;
                    long Days = (long) Math.ceil((double) node.getHandleDate() / 24);
                    if (hours > 0) {
                        millisecond = Days * 24 * 3600 * 1000;
                    }
                    Date currentDate = null;
                    //获取当前节点的配置的计算出的超期时间
                    currentDate = commonService.getDateFromStartByType(new Date(),
                            (int) Math.ceil((double) node.getHandleDate() / 24), millisecond,
                            node.getIsNaturalorWorkday());
                    currentDate = DateUtils.getDate(DateUtils.dateString(currentDate, "yyyy-MM-dd"), "yyyy-MM-dd");
                    timestatus.setNodeEndTime(currentDate);
                    timestatus.setNodeProcessTime((int) Math.ceil((double) hours / 24));
                    timestatus.setNodeSuspendMillisecond(millisecond);
                    timestatus.setDistributionEndTime(currentDate);
                }
                timestatus.setNodeTimeStatus(ScProductConstant.NORMAL);//写入节点超期状态,默认不超期
                timestatus.setOrderTimeStatus(ScProductConstant.NORMAL);
                timestatus.setCreaterId(userentity.getId());
                timestatus.setCreaterName(userentity.getRealName());
                timestatus.setCreateTime(new Date());
                timestatus.setOrderStartTime(new Date());
                timestatus.setCreaterOrgId(null == curentDept ? null : Long.parseLong(curentDept.get("id").toString()));
                timestatus.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
                double day = Double.valueOf(map.get("processingCycle").toString()) / 24;
                int tday = (int) Math.ceil(day);
                Date orderEndTime = commonService.getDateFromStartByType(new Date(),
                        tday, (long) tday * 24 * 3600 * 1000,
                        (int) map.get("cycleType"));
                timestatus.setOrderStartTime(new Date());
                timestatus.setOrderSuspendMillisecond((long) tday * 24 * 3600 * 1000);
                timestatus.setOrderProcessTimeType((int) map.get("cycleType"));
                timestatus.setOrderProcessTime(tday);
                timestatus.setOrderEndTime(DateUtils.getDate(DateUtils.dateString(orderEndTime, "yyyy-MM-dd"), "yyyy-MM-dd"));
                producttimestatusdao.iboosinsertSelective(timestatus);

                //插入生产订单数据
                ProductData data = new ProductData();
                data.setId(DggKeyWorker.nextId());
                data.setScProductId(productOrder.getId());
                data.setScProductNo(productOrder.getScProductOrderNo());
                data.setCreaterId(userentity.getId());
                data.setCreaterName(userentity.getRealName());
                data.setCreateTime(new Date());
                data.setCreaterOrgId(null == curentDept ? null : Long.parseLong(curentDept.get("id").toString()));
                data.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
                productdatadao.ibossInsertSelective(data);
                try {//发送失败就算了
                    if ("BUS_YT_ZZ_ZS".equals(productOrder.getBusinessProductCode())) {
                        String[] msgs = new String[]{DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")};
                        List<UserEntity> users;
                        String[] codes = new String[]{"ZZSC_ZS_ADMIN", "ZZSC_ZS_SUPER_ADMIN"};
                        users = userService.findUserByRoleCodesAndOrgs(codes, 0, product.getProductOrgId());
                        if (users == null) {
                            users = new ArrayList<>();
                        }
                        commonService.sendMsgByAsynchronous(users, msgs, "ZZSC_SC_NEW_SZ");//收证入库新增消息
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        //销售子订单map
        // zzProductMapList = obj.get("gsscProductMapList").toString();////测试
        return "success";
    }
    public boolean isExistOrder(Map params){
        Integer count = productDao.selectOderCount(params);
        if(count>0){
            return true;
        }
        return false;
    }

    /**
     * 接收企大顺分配的订单
     * zyou
     */
    @Transactional
    public void allotScOrder(@Validated QdsScOrderVo qdsScOrderVo) {
        //保存order,products,首先查询数据库是否存在相关销售单数据
        OrderVo orderVo = qdsScOrderVo.getOrderVo();
        Order oldOrder = orderservice.selectByOrderId(orderVo.getOrderId());
        LoginUser userEntity = qdsScOrderVo.getLoginUser();
        //生成订单
        Order order = getScOrder(oldOrder, orderVo, userEntity);
        //插入销售订单
        if(oldOrder==null){
            orderservice.ibossInsertQdb(order);
        }
        //取出所有的子订单数据
        List<GsScOrderVo> gsScOrderVos = qdsScOrderVo.getGsScOrderVos();
        for (GsScOrderVo gsScOrderVo : gsScOrderVos) {
            //保存产品以及生成生产单
            getProduct(gsScOrderVo, order, qdsScOrderVo,userEntity);
        }

    }

    /**
     * 生成订单
     */
    private Order getScOrder(Order oldOrder, OrderVo orderVo, LoginUser userEntity) {
        if(null == oldOrder) {
            oldOrder = new Order();
            oldOrder.setId(DggKeyWorker.nextId());//唯一主键
        }
        oldOrder.setOrderId(orderVo.getOrderId());
        oldOrder.setOrderNo(orderVo.getOrderNo());
        oldOrder.setScOrderNo(this.smsservice.getBillNumber("sc"));
        oldOrder.setBusinessId(orderVo.getBusinessId());
        oldOrder.setBusinessNo(orderVo.getBusinessNo());
        oldOrder.setCustomerId(orderVo.getCustomerId());
        oldOrder.setCustomerNo(orderVo.getCustomerNo());
        oldOrder.setCustomerPhone(orderVo.getContactPhone());
        oldOrder.setCustomerName(orderVo.getCustomerName());
        oldOrder.setContactPhone(orderVo.getContactPhone());
        oldOrder.setBusinessTypeId(null);
        oldOrder.setBusinessTypeName(orderVo.getBusinessTypeName());
        oldOrder.setSignUserId(orderVo.getBusinessUserId());
        oldOrder.setSignUserName(orderVo.getBusinessUserName());
        oldOrder.setScOrderSource(SystemCommonConstant.QDS_SC);
        Long signOrgId = orderVo.getSignOrgId();
        oldOrder.setSignUserOrgId(signOrgId);
        if (null != signOrgId) {
            Map deptMap = this.commonMangerExtService.findOrg(signOrgId);
            if (null != deptMap) {
                oldOrder.setSignUserOrgName(deptMap.get("name").toString());
            }
        }
        oldOrder.setSignOrgId(orderVo.getSignOrgId());
        oldOrder.setSignOrgName(orderVo.getSignOrgName());
        oldOrder.setMoney(orderVo.getAmount());
        oldOrder.setPayStatus(null);
        oldOrder.setPayMethod(null);
        oldOrder.setContractNo(orderVo.getContractNo());
        oldOrder.setSignDate(orderVo.getPlaceOrderTime());

        oldOrder.setCreaterId(Long.parseLong(userEntity.getUserId()));
        oldOrder.setCreaterName(userEntity.getRealName()+"/"+userEntity.getLoginName());
        oldOrder.setCreateTime(new Date());
        if(StringUtils.isNotEmpty(userEntity.getUserOrgId())){
            Map curentDept = this.commonMangerExtService.findOrg(Long.parseLong(userEntity.getUserOrgId()));
            oldOrder.setCreaterOrgId(null == curentDept ? null : Long.parseLong(curentDept.get("id").toString()));
            oldOrder.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
        }
        return oldOrder;
    }

    /**
     * 生成产品以及生产单
     * @param gsScOrderVo
     * @param order
     * @param qdsScOrderVo
     * @param userEntity
     * @return
     */
    public void getProduct(GsScOrderVo gsScOrderVo, Order order, QdsScOrderVo qdsScOrderVo, LoginUser userEntity){
        List<OrderBusinessVo> orderBusinessVos = gsScOrderVo.getOrderBusinessVos();
        for (OrderBusinessVo orderBusinessVo : orderBusinessVos) {
            Product product = new Product();//销售产品子订单
            product.setId(DggKeyWorker.nextId());
            product.setOrderId(order.getOrderId());

            product.setOrderBusinessId(orderBusinessVo.getOrderBusinessId());
            product.setBusinessTypeId(orderBusinessVo.getBtIdentifying());
            product.setOrderBusinessNo(orderBusinessVo.getOrderBusinessNo());
            product.setBusinessTypeName(orderBusinessVo.getSmallBusinessName());
            //这个关键字段必须要有值
            ValidateUtils.strNotEmpty(orderBusinessVo.getProductId(), CommonExcption.class, "该子订单没有产品ID,无法下单!");
            product.setBusinessProductCode(orderBusinessVo.getSmallBusiness() == null ? null : orderBusinessVo.getSmallBusiness().toString());
            product.setBusinessProductName(orderBusinessVo.getSmallBusinessName());
            product.setProductId(orderBusinessVo.getProductId());
            product.setProductName(orderBusinessVo.getProductName());
            product.setProductAttr(orderBusinessVo.getProductSpec());
            product.setServiceAreaId(null);
            product.setServiceArea(null);

            product.setContractNo(order.getContractNo());
            product.setOrderTime(order.getSignDate());
            product.setMoney(order.getMoney());
            product.setPayMethod(null);
            //这个证书用的费用状态写死
            product.setCostState("NOT_APPLAY");
            product.setProductOrgId(qdsScOrderVo.getProductOrgId());
            product.setProductOrgName(qdsScOrderVo.getProductOrgName());

            product.setCreaterId(Long.parseLong(userEntity.getUserId()));
            product.setCreaterName(userEntity.getRealName() + "/" + userEntity.getLoginName());
            product.setCreateTime(new Date());
            Map curentDept = null;
            if(StringUtils.isNotEmpty(userEntity.getUserOrgId())){
                curentDept = this.commonMangerExtService.findOrg(Long.parseLong(userEntity.getUserOrgId()));
            }
            product.setCreaterOrgId(null == curentDept ? null : Long.parseLong(curentDept.get("id").toString()));
            product.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            ProductOrder oldProductOrder = productOrderDao.selectByPrimaryKey(gsScOrderVo.getQdsScId());
            if(null != oldProductOrder){
                throw new CommonExcption("生产订单已生成，不可以重复分配！");
            }
            //生产订单表
            ProductOrder productOrder = new ProductOrder();
            productOrder.setId(gsScOrderVo.getQdsScId());
            productOrder.setScProductOrderNo(gsScOrderVo.getQdsScNo());
            productOrder.setOrderId(order.getOrderId());
            productOrder.setOrderNo(order.getOrderNo());
            productOrder.setOrderBusId(orderBusinessVo.getOrderBusinessId());
            productOrder.setOrderBusNo(orderBusinessVo.getOrderBusinessNo());
            productOrder.setBusinessId(order.getBusinessId());
            productOrder.setBusinessNo(order.getBusinessNo());
            productOrder.setCustomerId(order.getCustomerId());
            productOrder.setCustomerNo(order.getCustomerNo());
            productOrder.setCustomerPhone(order.getCustomerPhone());
            productOrder.setCustomerName(order.getCustomerName());
            productOrder.setContactPbone(order.getContactPhone());
            productOrder.setProductOrgId(product.getProductOrgId());
            productOrder.setProductOrgName(product.getProductOrgName());
            productOrder.setBusinessTypeCode(product.getBusinessTypeId());
            productOrder.setBusinessTypeName(product.getBusinessTypeName());
            productOrder.setBusinessProductCode(product.getBusinessProductCode());
            productOrder.setBusinessProductName(product.getBusinessProductName());
            productOrder.setProductId(product.getProductId());
            productOrder.setProductName(product.getProductName());
            productOrder.setIsMatching(0);
            CertificateProductConfiguration certificateProductConfiguration = certificateProductConfigurationService.selectQyByProductId(productOrder.getProductId());
            if(null != certificateProductConfiguration){
                //查询所需证书
                Map map = new HashMap();
                map.put("orderId",productOrder.getOrderId());
                map.put("orderBusId",productOrder.getOrderBusId());
                List<UnderOder> underOderList = underOrderDao.selectUnderOrderList(map);
                if(CollectionUtils.isEmpty(underOderList)){
                    throw new CommonExcption("请先完善底单信息，填写需预匹配证书类型！");
                }
                productOrder.setIsMatching(1);
                productOrder.setMatchingStatus(ScProductConstant.NOT_MATCHING);
            }else{
                productOrder.setMatchingStatus(ScProductConstant.NOT_NEED_MATCHING);
            }
            productOrder.setChannelId(null);
            productOrder.setChannelName(null);
            productOrder.setContractNo(product.getContractNo());
            productOrder.setOrderTime(product.getOrderTime());
            productOrder.setMoney(product.getMoney());
            productOrder.setPayMethod(product.getPayMethod());
            productOrder.setSignUserId(order.getSignUserId());
            productOrder.setSignUserName(order.getSignUserName());
            productOrder.setContractNo(order.getContractNo());
            productOrder.setSignUserOrgId(order.getSignUserOrgId());
            productOrder.setSignUserOrgName(order.getSignUserOrgName());
            productOrder.setSignOrgId(order.getSignOrgId());
            productOrder.setSignOrgName(order.getSignOrgName());
            productOrder.setSignTime(order.getSignDate());///签单时间需要增加此字段
            productOrder.setStatus(ScProductConstant.SC_TO_RECEIVE_XDDJS);//下单待分配
            productOrder.setRemark("分配订单");
            productOrder.setCreaterId(Long.parseLong(userEntity.getUserId()));
            productOrder.setCreaterName(userEntity.getRealName());
            productOrder.setCreateTime(new Date());
            productOrder.setCreaterOrgId(null == curentDept ? null : Long.parseLong(curentDept.get("id").toString()));
            productOrder.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            productOrder.setSignTime(order.getSignDate());
            productOrder.setOrderRemark("分配订单");
            //插入流程id
            String flowStr = flowService.getFlowNodeStr(product.getProductId().toString(), product.getBusinessTypeId(), product.getProductOrgId(),product.getBusinessProductCode());
            ValidateUtils.isTrue(StringUtils.isNotEmpty(flowStr), CommonExcption.class, "未查询到" + product.getBusinessTypeName() + "[" + product.getProductName() + "]流程节点的配置信息,请联系对应事业部后台负责人");
            List<Node> nodeList = flowService.getNodeByFlowContent(flowStr);
            Node nodeNew = new Node();
            if (!"BUS_YT_ZZ_ZS".equals(product.getBusinessProductCode())) {
                Node nodeNew1 = new Node();
                for (Node node : nodeList) {
                    if ("分配".equals(node.getName())) {
                        nodeNew = node;
                    }
                    if ("接单".equals(node.getName())) {
                        nodeNew1 = node;
                    }
                }
                ValidateUtils.isTrue(StringUtils.isNotEmpty(nodeNew.getName()), CommonExcption.class, "未查询到[" + product.getProductName() + "]的分配节点的信息,请联系对应事业部后台负责人");
                ValidateUtils.isTrue(StringUtils.isNotEmpty(nodeNew1.getName()), CommonExcption.class, "未查询到到[" + product.getProductName() + "]的接单节点的信息,请联系对应事业部后台负责人");
            } else {
                for (Node node : nodeList) {
                    if ("证书入库".equals(node.getName())) {
                        nodeNew = node;
                    }
                }
                ValidateUtils.isTrue(StringUtils.isNotEmpty(nodeNew.getName()), CommonExcption.class, "未查询到到[" + product.getProductName() + "]的证书入库节点的信息,请联系对应事业部后台负责人");
            }
            Node node = nodeNew;
            productOrder.setFlowContent(flowStr);
            Map map = flowService.getOderCycle(productOrder);
            productOrder.setCurrentNodeId(node.getCode());
            productOrder.setCurrentNodeName(node.getName());
            productOrder.setLatestEndNodeId(node.getId().toString());
            productOrder.setLatestEndNodeName(node.getName());
            productOrderDao.iboosInsertSelective(productOrder);
            product.setRelevanceCredential(0);
            product.setCostState(ScProductConstant.NOT_APPLAY);
            product.setScProductOrderId(productOrder.getId());
            product.setScProductOrderNo(productOrder.getScProductOrderNo());
            product.setScOrderSource(SystemCommonConstant.QDS_SC);
            product.setQdsScId(orderBusinessVo.getQdsScId());
            product.setQdsScNo(orderBusinessVo.getQdsScNo());
            productservice.iboosInsertProductQdb(product);

            //插入操作记录
            SystemRecord record = new SystemRecord();
            record.setId(DggKeyWorker.nextId());//id
            record.setSource("3");
            record.setWorkTableName("zzsc_product_order");
            record.setWorkId(productOrder.getId());
            record.setWorkNo(productOrder.getScProductOrderNo());
            record.setBeOperaterId(Long.parseLong(userEntity.getUserId()));
            record.setOperateType("1");
            record.setRemarks("新增生产订单");
            systemRecordService.apiQdbSave(record, userEntity);

            //生产订单超期
            ProductTimeStatus timestatus = new ProductTimeStatus();
            timestatus.setId(productOrder.getId());
            timestatus.setScProductOrderNo(productOrder.getScProductOrderNo());
            timestatus.setDistributionStartTime(new Date());//计时开始时间
            timestatus.setDistributionTimeOutStatus(ScProductConstant.NORMAL);
            timestatus.setFlag(1);//必须要加入
            //写入分配节点
            Integer hours = 0;
            if (null != node) {
                timestatus.setNodeId(node.getCode());
                timestatus.setNodeName(node.getName());
                hours = node.getHandleDate();
                timestatus.setNodeProcessTimeType(node.getIsNaturalorWorkday());
                timestatus.setNodeStartTime(new Date());
                long millisecond = 0l;
                long Days = (long) Math.ceil((double) node.getHandleDate() / 24);
                if (hours > 0) {
                    millisecond = Days * 24 * 3600 * 1000;
                }
                Date currentDate = null;
                //获取当前节点的配置的计算出的超期时间
                currentDate = commonService.getDateFromStartByType(new Date(),
                        (int) Math.ceil((double) node.getHandleDate() / 24), millisecond,
                        node.getIsNaturalorWorkday());
                currentDate = DateUtils.getDate(DateUtils.dateString(currentDate, "yyyy-MM-dd"), "yyyy-MM-dd");
                timestatus.setNodeEndTime(currentDate);
                timestatus.setNodeProcessTime((int) Math.ceil((double) hours / 24));
                timestatus.setNodeSuspendMillisecond(millisecond);
                timestatus.setDistributionEndTime(currentDate);
            }
            timestatus.setNodeTimeStatus(ScProductConstant.NORMAL);//写入节点超期状态,默认不超期
            timestatus.setOrderTimeStatus(ScProductConstant.NORMAL);
            timestatus.setCreaterId(Long.parseLong(userEntity.getUserId()));
            timestatus.setCreaterName(userEntity.getRealName());
            timestatus.setCreateTime(new Date());
            timestatus.setOrderStartTime(new Date());
            timestatus.setCreaterOrgId(null == curentDept ? null : Long.parseLong(curentDept.get("id").toString()));
            timestatus.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            long day = (long) Math.ceil(Double.parseDouble(map.get("processingCycle").toString()) / 24);
            Integer cycleType = Integer.parseInt(String.valueOf(map.get("cycleType")));
            int tday = (int) Math.ceil(day);
            Long ms = day * 24 * 3600 * 1000;
            Date orderEndTime = commonService.getDateFromStartByType(new Date(),tday, ms, cycleType);
            timestatus.setOrderStartTime(new Date());
            timestatus.setOrderSuspendMillisecond((long) tday * 24 * 3600 * 1000);
            timestatus.setOrderProcessTimeType((int) map.get("cycleType"));
            timestatus.setOrderProcessTime(tday);
            timestatus.setOrderEndTime(DateUtils.getDate(DateUtils.dateString(orderEndTime, "yyyy-MM-dd"), "yyyy-MM-dd"));
            producttimestatusdao.iboosinsertSelective(timestatus);

            //插入生产订单数据
            ProductData data = new ProductData();
            data.setId(DggKeyWorker.nextId());
            data.setScProductId(productOrder.getId());
            data.setScProductNo(productOrder.getScProductOrderNo());
            data.setCreaterId(Long.parseLong(userEntity.getUserId()));
            data.setCreaterName(userEntity.getRealName());
            data.setCreateTime(new Date());
            data.setCreaterOrgId(null == curentDept ? null : Long.parseLong(curentDept.get("id").toString()));
            data.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            productdatadao.ibossInsertSelective(data);
            try {//发送失败就算了
                if ("BUS_YT_ZZ_ZS".equals(productOrder.getBusinessProductCode())) {
                    String[] msgs = new String[]{DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")};
                    List<UserEntity> users;
                    String[] codes = new String[]{"ZZSC_ZS_ADMIN", "ZZSC_ZS_SUPER_ADMIN"};
                    users = userService.findUserByRoleCodesAndOrgs(codes, 0, product.getProductOrgId());
                    if (users == null) {
                        users = new ArrayList<>();
                    }
                    commonService.sendMsgByAsynchronous(users, msgs, "ZZSC_SC_NEW_SZ");//收证入库新增消息
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //需判断是不是证书
            if (!"BUS_YT_ZZ_ZS".equals(product.getBusinessProductCode())) {
                this.allotScOrder(productOrder.getId(),userEntity, qdsScOrderVo.getFlowerId());
            }
        }
    }

    /**
     * 订单分配
     * @param id
     * @param currentUser
     * @return
     */
    public void allotScOrder(Long id,LoginUser currentUser,Long flowUserId) {
        Map param = new HashMap();
        param.put("id",id);
        String allotWay = ScProductConstant.ALLOT_TO_PRODUCT_USER;//分配方式
        param.put("allotWay",allotWay);
        ProductOrder order = productOrderDao.selectByPrimaryKey(id);
        ProductTimeStatus timestatus = productTimeStatusDao.selectByPrimaryKey(order.getId());
        //保存节点开始结束时间
        Date nodeStartTime = null;
        Date nodeEndTime = null;
        //判断当前订单的分配方式 如果是部门分配需要重新计数超期时间，其他分配方式从超期计算表中取
        if("分配" != timestatus.getNodeName()){
            nodeStartTime = order.getCreateTime();
            if(!StringUtils.isEmpty(order.getFlowContent())){
                //新流程
                List<Node> nodelist = flowService.getNode(id);
                if (nodelist.size() == 0) {
                    throw new CommonExcption("未配置流程！");
                }
                Node newNode = flowService.queyNodeListByName("分配", order.getId());
                if(null != newNode.getName()) {
                    nodeEndTime = commonService.getDateFromStartByType(null == order.getLatestEndNodeTime() ? order.getUpdateTime() : order.getLatestEndNodeTime(),
                            (int) Math.ceil((double)newNode.getHandleDate() / 24), (long) Math.ceil((double)newNode.getHandleDate() / 24) * 24 * 3600*1000,
                            newNode.getIsNaturalorWorkday());
                    nodeEndTime =  DateUtils.getDate(DateUtils.dateString(nodeEndTime,"yyyy-MM-dd"),"yyyy-MM-dd");
                }else{
                    nodeEndTime = commonService.getDateFromStartByType(order.getCreateTime(),1,  24l * 3600*1000,1);
                    nodeEndTime =  DateUtils.getDate(DateUtils.dateString(nodeEndTime,"yyyy-MM-dd"),"yyyy-MM-dd");
                }
            }else{
                //老流程默认1个工作日
                nodeEndTime = commonService.getDateFromStartByType(order.getCreateTime(),1,  24l * 3600*1000,1);
                nodeEndTime =  DateUtils.getDate(DateUtils.dateString(nodeEndTime,"yyyy-MM-dd"),"yyyy-MM-dd");
            }
        }else {
            nodeStartTime = timestatus.getNodeStartTime();
            nodeEndTime = timestatus.getNodeEndTime();
        }
        int a = DateUtils.compare_date(new Date(), nodeEndTime);
        if (!order.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_XDDJS) && !order.getStatus().equals(ScProductConstant.SC_ORDER_BACK_TO_ALLOT)
                && !order.getStatus().equals(ScProductConstant.SC_ORDER_WAIT_ALLOT)) {
            //如果当前状态不是待分配状态或者事业部移交待分配
            throw new CommonExcption("当前订单状态已改变，不能进行分配");
        }
        if(!StringUtils.isEmpty(order.getFlowContent())) {
            //获取流程节点
            List<Node> nodelist = flowService.getNode(id);
            if (nodelist.size() == 0) {
                throw new CommonExcption("未配置流程！");
            }
            Node finishNode = flowService.queyNodeListByName("分配", order.getId());
            if (null == timestatus.getNodeEndTime()) {
                Date newDate = null;
                //获取当前节点的配置的计算出的超期时间
                newDate = commonService.getDateFromStartByType(new Date(),
                        (int) Math.ceil(finishNode.getHandleDate() / 24), (long) Math.ceil((double)finishNode.getHandleDate() / 24) * 24 * 3600*1000,
                        finishNode.getIsNaturalorWorkday());
                timestatus.setNodeEndTime(newDate);
            }
            if (a == 1) {
                if ((null == order.getPunishStatus() || 0 == order.getPunishStatus()) && null != timestatus.getNodeEndTime() && finishNode.getIsPunish()==1) {
                    Map currentMap = null;
                    if(StringUtils.isNotEmpty(currentUser.getUserOrgId())){
                        currentMap = this.commonMangerExtService.findOrg(Long.parseLong(currentUser.getUserOrgId()));
                    }
                    if (null != currentMap) {
                        order.setFlowUserOrgId(Long.valueOf(currentMap.get("id").toString()));
                        order.setFlowUserOrgName(currentMap.get("name").toString());
                        order.setFlowUserId(Long.parseLong(currentUser.getUserId()));
                        order.setFlowUserName(currentUser.getRealName().concat(currentUser.getLoginName()));
//                        order.setReceiverId(Long.parseLong(currentUser.getUserId()));
//                        order.setReceiverName(currentUser.getRealName().concat(currentUser.getLoginName()));
//                        order.setReceiveTime(new Date());
                        Integer code = zzInProcessService.nodeTimeOutPunish(order, finishNode, timestatus);
                        if (code == 0) {
                            if("成都资质事业部".equals(order.getProductOrgName())){
                                //发送扣罚消息
                                try {//不让影响其他功能
                                    //扣罚人
                                    UserEntity user = userService.findUserById(order.getFlowUserId());
                                    List<UserEntity> users = new ArrayList<>();
                                    users.add(user);
                                    //1.生产订单节点奖罚：您好，{生产订单编号}{客户名称}{订单产品}，xx节点超期产生扣罚，请查看确认。
                                    String msg[] = new String[]{order.getScProductOrderNo(),order.getCustomerName(),order.getProductName(),finishNode.getName()};
                                    commonService.sendMsgByAsynchronous(users, msg, "ZZSC_NODE_PUNISH_ALERT");//匹配模板
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }

                }
            }
            Node node = new Node();
            if (nodelist.size() > 0) {
                node = flowService.queyNodeListByName("接单", order.getId());
                param.put("currentNodeId", node.getId());
                param.put("currentNodeName", node.getName());
            }
            //写入下个节点信息
            long currentTime = System.currentTimeMillis();
            Date date = new Date(currentTime);
            Integer hours = 0;
            if (null != node) {
                timestatus.setNodeId(node.getId().toString());
                timestatus.setNodeName(node.getName());
                timestatus.setNodeProcessTimeType(node.getIsNaturalorWorkday());
                timestatus.setNodeStartTime(date);
                long millisecond = 0;
                long Days = (long) Math.ceil((double)node.getHandleDate() / 24);
                hours = node.getHandleDate();
                if (hours > 0) {
                    millisecond = Days * 24 * 3600*1000;
                }
                Date currentDate = null;
                //获取当前节点的配置的计算出的超期时间
                currentDate = commonService.getDateFromStartByType(date,
                        (int) Math.ceil((double)node.getHandleDate() / 24), millisecond,
                        node.getIsNaturalorWorkday());
                currentDate = DateUtils.getDate(DateUtils.dateString(currentDate,"yyyy-MM-dd"),"yyyy-MM-dd");
                timestatus.setNodeEndTime(currentDate);
                timestatus.setNodeProcessTime((int) Math.ceil((double)hours / 24));
                timestatus.setNodeSuspendMillisecond(millisecond);
                timestatus.setReceiveEndTime(currentDate);
            }
        }
        //写入下一个节点
        if(StringUtils.isEmpty(order.getFlowContent())){
            List<ProductNode> nodelist = zzInProcessService.queyNodeList(order.getNodeFlowId());
            for (ProductNode scProductNode : nodelist) {
                if (null != scProductNode.getName() && !"".equals(scProductNode.getName()) && "接单".equals(scProductNode.getName())) {
                    param.put("currentNodeName", scProductNode.getName());
                    param.put("currentNodeId", scProductNode.getId());
                    break;
                }
            }

        }
        Long receiverId = flowUserId;//分配人员id
        param.put("receiverId",flowUserId);
        UserEntity userEntity = userService.findUserById(receiverId);//查询接收人
        if (null == userEntity) {
            throw new CommonExcption("分配失败,未查询到接收人信息");
        }
        Map map = this.commonMangerExtService.findOrg(userEntity.getOrgId());
        if (null != map) {
            if (allotWay.equals(ScProductConstant.ALLOT_TO_PRODUCT_USER)) {//分配给负责人
                param.put("productUserId", userEntity.getId());
                param.put("productUserName", userEntity.getRealName() + userEntity.getLoginName());
                param.put("productUserOrgId", map.get("id"));
                param.put("productUserOrgName", map.get("name"));
            }
            param.put("receiverId", userEntity.getId());
            param.put("receiverName", userEntity.getRealName() + userEntity.getLoginName());
            param.put("receiverOrgId", map.get("id"));
            param.put("receiverOrgName", map.get("name"));
            //为了保证异常订单正常工作, 分配的时候把流程人员写进去
            param.put("flowUserId", userEntity.getId());
            param.put("flowUserName", userEntity.getRealName() + userEntity.getLoginName());
            param.put("flowUserOrgId", map.get("id"));
            param.put("flowUserOrgName", map.get("name"));
            order.setFlowUserId(userEntity.getId());
            order.setFlowUserName(userEntity.getRealName() + userEntity.getLoginName());
            param.put("allotWay", allotWay);//分配方式
            param.put("allotUserId", currentUser.getUserId());
            param.put("allotUserName", currentUser.getRealName() + currentUser.getLoginName());
            param.put("allotUserOrgId", currentUser.getUserOrgId());
            param.put("allotUserOrgName", map.get("name"));
            param.put("allotDate", new Date());//分配时间
            // 如果无需办理直接进入完结列表
            if(!StringUtils.isEmpty(order.getFlowContent())) {
                List<Node> nodelist1 = flowService.getNode(id);
                param.put("status", ScProductConstant.SC_TO_RECEIVE_FPDJS);//分配待接收状态
                param.put("latestEndNodeId", order.getLatestEndNodeId());
                param.put("latestEndNodeName", order.getLatestEndNodeName());
                param.put("latestEndNodeTime", new Date());//设置最新更新节点时间
            }else{
                param.put("status", ScProductConstant.SC_TO_RECEIVE_FPDJS);//分配待接收状态
                param.put("latestEndNodeId", order.getLatestEndNodeId());
                param.put("latestEndNodeName", order.getLatestEndNodeName());
                param.put("latestEndNodeTime", new Date());//设置最新更新节点时间
            }
            param.put("updaterId", currentUser.getUserId());
            param.put("updaterName", currentUser.getRealName() + currentUser.getLoginName());
            param.put("updaterOrgId", currentUser.getUserOrgId());
            param.put("updaterOrgName", map.get("name"));
            param.put("updateTime", new Date());
            param.put("originCode", ScProductConstant.ORDER_SOURCE_DISTRIBUTION);
            productOrderDao.distributionProductOrder(param);
            int i = DateUtils.compare_date(new Date(), timestatus.getDistributionEndTime());
            if (i == 1) {
                timestatus.setDistributionTimeOutStatus(ScProductConstant.TIME_OUT);
            } else {
                timestatus.setDistributionTimeOutStatus(timestatus.getDistributionTimeOutStatus());
            }
            timestatus.setReceiveStartTime(new Date());
            timestatus.setReceiveProcessTime(1);

            try {
                timestatus.setReceiveTimeStatus(ScProductConstant.NORMAL);
            } catch (Exception e) {
                e.printStackTrace();
            }
            timestatus.setNodeTimeStatus(ScProductConstant.NORMAL);
            productTimeStatusDao.updateTimeOutStatus(timestatus);
            //插入操作记录
            SystemRecord record = new SystemRecord();
            record.setId(DggKeyWorker.nextId());//id
            record.setSource("2");
            record.setWorkTableName("zzsc_product_order");
            record.setWorkId(order.getId());
            record.setWorkNo(order.getScProductOrderNo());
            record.setBeOperaterId(receiverId);
            record.setOperateType("17");
            record.setRemarks("订单分配");
            systemRecordService.saveQdb(record, currentUser);
            if(!StringUtils.isEmpty(order.getFlowContent())) {
                List<Node> nodelist = flowService.getNode(id);
                Node finishNode = flowService.queyNodeListById(order.getLatestEndNodeId() == null ? nodelist.get(0).getId().toString() : order.getLatestEndNodeId(), order.getId());
                // 添加节点操作记录
                ProductNodeOperating scProductNodeOperating = new ProductNodeOperating();
                scProductNodeOperating.setId(DggKeyWorker.nextId());
                scProductNodeOperating.setRemarksType(1);   //(记录类型  1：节点更新，2：备注)
                scProductNodeOperating.setScProductOrderId(order.getId());
                scProductNodeOperating.setScProductOrderNo(order.getScProductOrderNo());
                scProductNodeOperating.setFlowOrgId(Long.parseLong(map.get("id").toString()));
                scProductNodeOperating.setFlowOrgName(map.get("name").toString());
                scProductNodeOperating.setFlowUserId(Long.parseLong(currentUser.getUserId()));
                scProductNodeOperating.setFlowUserName(currentUser.getRealName().concat(currentUser.getLoginName()));
                scProductNodeOperating.setNodeId(order.getLatestEndNodeId());
                scProductNodeOperating.setOrderStatus(param.get("status").toString());
                scProductNodeOperating.setNodeName(order.getLatestEndNodeName());
                scProductNodeOperating.setNodeProcessTimeType(finishNode.getIsNaturalorWorkday().toString()); //节点办理类型
                scProductNodeOperating.setNodeOpetateTime(new Date());
                scProductNodeOperating.setIsExtract(finishNode.getIsExtract());
                Map curOrg = commonMangerExtService.findOrg(userEntity.getOrgId());
                scProductNodeOperating.setCreaterOrgName(curOrg.get("name").toString());
                scProductNodeOperating.setRemark("节点更新操作");
                if (a == 1) {
                    scProductNodeOperating.setNodeTimeStatus(ScProductConstant.TIME_OUT); //节点超期状态
                } else {
                    scProductNodeOperating.setNodeTimeStatus(ScProductConstant.NORMAL); //节点未超期状态
                }
                scProductNodeOperating.setNodeProcessTime((int) Math.ceil((double)finishNode.getHandleDate() / 24));
                scProductNodeOperating.setNodeStartTime(nodeStartTime);
                scProductNodeOperating.setNodeEndTime(nodeEndTime);
                //佣金类型
                scProductNodeOperating.setCommission(finishNode.getCommission());
                //佣金金额
                scProductNodeOperating.setBrokerage(finishNode.getBrokerage());
                //保存更新节点数据
                this.saveOpt(scProductNodeOperating, userEntity);
                productNodeOperatingDao.insert(scProductNodeOperating);
            }
            try {
                //通过MQ推送消息到UC
                CustomerRecord customerRecord = new CustomerRecord();
                customerRecord.setCustomerId(order.getCustomerId());
                customerRecord.setTableName("zzsc_product_order");
                customerRecord.setTableId(order.getId());
                customerRecord.setTableNo(order.getScProductOrderNo());
                customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE5);
                customerRecord.setCreaterId(Long.parseLong(currentUser.getUserId()));
                MQMessageSendUtil.ucMessageSend(customerRecord);

                //提交之后，将订单信息同步到企大顺生产中心
                MQMessageSendUtil.qdsMessageSend(order, null,  userEntity);

                String[] msgs = new String[]{order.getScProductOrderNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")};
                List<UserEntity> users = new ArrayList<>();
                users.add(userEntity);//接收人
                commonService.sendMsgByAsynchronous(users, msgs, "ZZSC_SC_ALLOT");//分配模板
                //发送企管家消息
                String conent="您好，您的客户"+order.getCustomerName()+"订单"+order.getOrderNo()+"办理的"+order.getScProductOrderNo()+"业务,分配节点已更新,请及时查看沟通";
                commonService.sendQgjMessage(order.getOrderId(),order.getBusinessTypeCode(),userEntity.getId(),userEntity.getRealName(),
                        userEntity.getLoginName(),conent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            throw new CommonExcption("分配失败,请联系管理员！");
        }
    }

    /**
     * 根据生产单id查询生产单的办理团队
     * @param scOrderId
     * @return
     */
    public List<Map> getScOrderManagementTeam(String scOrderId) {
        return productNodeOperatingDao.getScOrderManagementTeam(scOrderId);
    }
}

